<template>
  <t-form ref="form" class="item-container" :data="formData" :rules="FORM_RULES" label-width="0" @submit="onSubmit">
    <t-form-item name="username">
      <t-input v-model="formData.username" size="large" :placeholder="`${$t('pages.login.input.username')}`">
        <template #prefix-icon>
          <t-icon name="user" />
        </template>
      </t-input>
    </t-form-item>

    <t-form-item name="password">
      <t-input
        v-model="formData.password"
        size="large"
        :type="showPsw ? 'text' : 'password'"
        clearable
        :placeholder="`${$t('pages.login.input.password')}`"
      >
        <template #prefix-icon>
          <t-icon name="lock-on" />
        </template>
        <template #suffix-icon>
          <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw" />
        </template>
      </t-input>
    </t-form-item>

    <t-form-item name="code" class="form-code">
      <t-input
        v-model="formData.code"
        size="large"
        type="text"
        clearable
        maxlength="4"
        :placeholder="`${$t('pages.login.input.verification')}`"
      >
        <template #prefix-icon>
          <t-icon name="gesture-up-1" />
        </template>
      </t-input>
      <div class="codeimg" @click="getCode" v-html="coder"></div>
    </t-form-item>

    <t-form-item class="btn-container">
      <t-button block size="large" type="submit"> {{ $t('pages.login.signIn') }} </t-button>
    </t-form-item>
  </t-form>
</template>

<script setup lang="ts">
import type { SubmitContext } from 'tdesign-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import $api from '@/api/';
import { t } from '@/locales';
import { useUserStore } from '@/store';

import { FORM_DATA, FORM_RULES } from '../constants';

const userStore = useUserStore();

const formData = ref({ ...FORM_DATA });
const showPsw = ref(false);

const router = useRouter();
const route = useRoute();

// 获取验证码
const coder = ref('');
const getCode = async () => {
  coder.value = await $api.common.getCode();
};

const onSubmit = async (ctx: SubmitContext) => {
  if (ctx.validateResult === true) {
    try {
      const data = await $api.common.login(formData.value);
      userStore.setUserInfo(data);

      MessagePlugin.success(t('pages.login.loginSuccess'));
      const redirect = route.query.redirect as string;
      const redirectUrl = redirect ? decodeURIComponent(redirect) : '/dashboard';
      router.push(redirectUrl);
    } catch (e) {
      console.log(e);
      MessagePlugin.error(e.message);
    }
  }
};

onMounted(() => {
  getCode();
});
</script>

<style lang="less" scoped>
@import '../index.less';
</style>
